package org.geektimes.configuration.microprofile.config.source;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;

public class ServletRequestConfigSource extends MapBasedConfigSource {

	protected ServletRequest request;

	public ServletRequestConfigSource() {
		super("ServletRequestConfigSource", 500);
	}

	public void setServletRequest(ServletRequest request) {
		this.request = request;
	}

	public Object getProperty(String key) {
		String[] values = request.getParameterValues(key);

		List<Object> result = null;
		if (values == null || values.length == 0) {
			return null;
		} else if (values.length == 1) {
			result = new ArrayList<Object>(1);
			result.add(values[0]);
			return result;
		} else {
			result = new ArrayList<Object>(values.length);
			for (int i = 0; i < values.length; i++) {
				Object val = values[i];
				if (val instanceof Collection) {
					result.addAll((Collection<?>) val);
				} else {
					result.add(val);
				}
			}
			return result;
		}
	}

	public Iterator<String> getKeys() {
		// According to the documentation of getParameterMap(), keys are Strings.
		@SuppressWarnings("unchecked")
		Map<String, ?> parameterMap = request.getParameterMap();
		return parameterMap.keySet().iterator();
	}

	/**
	 * 
	 */
	@Override
	public void prepareConfigData(Map configData) {
		Enumeration names = request.getParameterNames();
		Map<String,String> map = new HashMap<>();
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			String value = request.getParameter(name);
			map.put(name, value);
			System.out.println(name + " = " + value);
		}
		configData.putAll(map);
	}

}
